package cn.congine.wizarpos.mall.dao.hibernate;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import cn.congine.wizarpos.mall.dao.WxOrderDetailDao;
import cn.congine.wizarpos.mall.model.WxOrderDetail;
import cn.congine.wizarpos.mall.utils.Function;

@Repository("wxOrderDetailDao")
public class WxOrderDetailDaoHibernate extends
		GenericDaoHibernate<WxOrderDetail> implements WxOrderDetailDao {

	public WxOrderDetailDaoHibernate() {
		super(WxOrderDetail.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<WxOrderDetail> getWxOrderDetailListByOrderId(String orderId) {
		Query query = getSession().createQuery(
				"from WxOrderDetail where orderId = :orderId").setParameter(
				"orderId", orderId);
		return (List<WxOrderDetail>) query.list();
	}

	@Override
	public WxOrderDetail getWxOrderDetailByProductId(String productId) {
		Query query = getSession().createQuery(
				"from WxOrderDetail where productId=:productId ").setParameter(
				"productId", productId);
		return (WxOrderDetail) query.uniqueResult();
	}

	@Override
	public void removeByOrderId(String mid, String orderId) {
		String hql = "delete From WxOrderDetail where mid = ? and orderId = ?";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createQuery(hql);
		q.setString(0, mid);
		q.setString(1, orderId);
		q.executeUpdate();
	}

	@Override
	public WxOrderDetail save(WxOrderDetail obj) {
		String uuid = Function.getUid();
		obj.setId(uuid);

		String sql = "INSERT INTO wx_order_detail (id, mid, order_id, product_id, CODE,"
				+ " product_name, amount, price, qty, last_time)"
				+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createSQLQuery(sql);

		q.setString(0, uuid);
		q.setString(1, obj.getMid());
		q.setString(2, obj.getOrderId());
		q.setString(3, obj.getProductId());
		q.setString(4, obj.getCode());
		q.setString(5, obj.getProductName());
		q.setInteger(6, obj.getAmount());
		q.setInteger(7, obj.getPrice());
		q.setInteger(8, obj.getQty());
		q.setLong(9, obj.getLastTime());

		q.executeUpdate();

		return obj;
	}

}
